<?php

namespace app\shop\model\order;

use app\shop\enums\order\OrderStatus;
use app\shop\model\BaseModel;
use app\shop\model\PaymentTradeModel;
use app\shop\model\user\UserModel;
use think\model\concern\SoftDelete;
use think\model\relation\BelongsTo;
use think\model\relation\HasMany;
use think\model\relation\HasOne;

class OrderModel extends BaseModel
{
    // 软删除
    use SoftDelete;

    protected $name = 'shop_order';

    protected $type = [
        'coupon_info'     => 'json',
        'discount_data'   => 'json',
        'discount_detail' => 'json',
        'create_time'     => 'timestamp:Y-m-d H:i:s',
        'update_time'     => 'timestamp:Y-m-d H:i:s',
        'delete_time'     => 'timestamp:Y-m-d H:i:s',
        'pay_time'        => 'timestamp:Y-m-d H:i:s',
    ];

    protected $jsonAssoc = true;

    /**
     * 关联订单详情
     * @return HasMany
     */
    public function detail(): HasMany
    {
        return $this->hasMany(OrderDetailModel::class, 'order_id', 'id');
    }

    /**
     * 关联订单地址
     * @return HasOne
     */
    public function address(): HasOne
    {
        return $this->hasOne(OrderAddressModel::class, 'order_id', 'id');
    }

    /**
     * 关联用户
     * @return BelongsTo
     */
    public function user(): BelongsTo
    {
        return $this->belongsTo(UserModel::class, 'user_id', 'id');
    }

    /**
     * 关联发货记录
     * @return HasMany
     */
    public function delivery(): HasMany
    {
        return $this->hasMany(OrderDeliveryModel::class, 'order_id', 'id');
    }

    /**
     * 关联第三方支付
     * @return HasOne
     * @noinspection PhpUnused
     */
    public function paymentTrade(): HasOne
    {
        return $this->hasOne(PaymentTradeModel::class, 'out_trade_no', 'out_trade_no');
    }

    /**
     * @param $value
     * @param $data
     * @return int|mixed
     * @noinspection PhpUnused
     * @noinspection PhpUnusedParameterInspection
     */
    public function getCountDownAttr($value, $data): mixed
    {
        if ($data['status'] != OrderStatus::TO_PAT) {
            return -1;
        }

        $time = $data['final_pay_time'] - time();

        return max($time, -1);
    }
}
